<?php

class Home extends TPage
{
	private $monthNames = array(
		'január'     => '01',
		'február'    => '02',
		'március'    => '03',
		'április'    => '04',
		'május'      => '05',
		'június'     => '06',
		'július'     => '07',
		'augusztus'  => '08',
		'szeptember' => '09',
		'október'    => '10',
		'november'   => '11',
		'december'   => '12'
	);
	protected $defaultSortDirection = 'ASC';
	private $rowColorSortExpression = 'row_color';
	private $birthdateRegex = '/^\\s*(\\S*)\\s*\\.\\s*(\\S*)\\s*(\\S*)\\s*\\.\\s*$/';
	private $namedayRegex = '/^\\s*(\\S*)\\s*(\\S*)\\s*\\.\\s*$/';
	public function onPreInit($parameters)
	{
		setlocale(LC_ALL, 'hu_HU');
		if ($_SERVER['SERVER_NAME'] === 'localhost')
		{
			mysql_connect('localhost', 'root', '');
			mysql_select_db('test');
		} else {
			mysql_connect('localhost', 'kincsker', '');
			mysql_select_db('kincsker_naptar');
		}
		mysql_query('set names utf8');
		mysql_query('set lc_time_names hu_HU');
	}
	public function onUnload($parameters)
	{
		mysql_close();
	}
	public function onLoad($parameters)
	{
		if (!$this->IsPostBack)
		{
			if ($this->hdnSortExpression->Value !== 'row_color')
				$this->hdnSortDirection->Value = $this->defaultSortDirection;
			else
				$this->hdnSortDirection->Value = 'DESC';
			$this->dgrMain->PageSize = $this->ddlPageSize->SelectedValue;
			$this->PopulateDataGrid();
		}
	}
	private function PopulateDataGridBase($addNewRow)
	{
		if (empty($sortExpression)) $sortExpression = 'name';
		$this->dgrMain->VirtualItemCount = $this->VirtualItemCount;
		$utolsoLehetsegesOldalSzam = ceil($this->dgrMain->VirtualItemCount / $this->dgrMain->PageSize) - 1;
		if ($this->dgrMain->CurrentPageIndex > $utolsoLehetsegesOldalSzam )
		{
			$this->dgrMain->CurrentPageIndex =
				$utolsoLehetsegesOldalSzam;
		}
		if ($addNewRow)
		{
			$this->dgrMain->CurrentPageIndex =
				ceil(
					(($this->dgrMain->VirtualItemCount + 1) /
					$this->dgrMain->PageSize)) - 1;
		}
		$dataSet = 
			$this->RetrieveData(
				$this->dgrMain->CurrentPageIndex * $this->dgrMain->PageSize,
				$this->dgrMain->PageSize);
		if ($addNewRow)
		{
			$this->dgrMain->VirtualItemCount++;
			$dataSet[] = array(
				'id' => -1,
				'name' => '',
				'birthdate' => '',
				'nameday' => '',
				'father' => ''
			);
			$this->dgrMain->EditItemIndex =
				( $this->dgrMain->VirtualItemCount % $this->dgrMain->PageSize ) - 1;
			if ($this->dgrMain->EditItemIndex === -1)
				$this->dgrMain->EditItemIndex = $this->dgrMain->PageSize - 1;
		}
		$this->dgrMain->DataSource = $dataSet;
		$this->dgrMain->DataBind();
	}
	private function PopulateDataGrid()
	{
		$this->PopulateDataGridBase(false);
	}
	private function PopulateDataGridAddNew()
	{
		$this->PopulateDataGridBase(true);
	}
	protected function dgrMain_EditCommand($sender, $parameters)
	{
		$this->dgrMain->EditItemIndex = $parameters->Item->ItemIndex;
		$this->PopulateDataGrid();
	}
	protected function dgrMain_CancelCommand($sender, $parameters)
	{
		$this->dgrMain->EditItemIndex = -1;
		$this->PopulateDataGrid();
	}
	protected function dgrMain_DeleteCommand($sender, $parameters)
	{
		$this->dgrMain->EditItemIndex = -1;
		$this->DeleteRow($this->dgrMain->DataKeys[$parameters->Item->ItemIndex]);
		$this->PopulateDataGrid();
	}
	protected function dgrMain_UpdateCommand($sender, $parameters)
	{
		$entity['id'] =
			$this->dgrMain->DataKeys[$parameters->Item->ItemIndex];
		$entity['name'] =
			$parameters->Item->dgrMain_Name->TextBox->Text;
		$entity['row_color'] =
			$parameters->Item->dgrMain_RowColor->TextBox->Text;
		$entity['comment'] =
			$parameters->Item->dgrMain_Comment->TextBox->Text;
		$entity['address'] =
			$parameters->Item->dgrMain_Address->TextBox->Text;
		$birthdateText = 
			$parameters->Item->dgrMain_Birthdate->dtpBirthdate->Date;
		if (!empty($birthdateText))
		{
			preg_match(
				$this->birthdateRegex, 
				$birthdateText, 
				$birthdate);
			$entity['birthdate'] =
				$birthdate[1].'-'.$this->monthNames[$birthdate[2]].'-'.$birthdate[3];
		}
		$namedayText =
			$parameters->Item->dgrMain_Nameday->dtpNameday->Date;
		if (!empty($namedayText))
		{
			preg_match(
				$this->namedayRegex, 
				$namedayText, 
				$nameday); 
			$entity['nameday'] =
				'2000-'.$this->monthNames[$nameday[1]].'-'.$nameday[2];
		}
		$entity['father'] =
			$parameters->Item->dgrMain_Father->DropDownList->SelectedValue;
		$entity['mother'] =
			$parameters->Item->dgrMain_Mother->DropDownList->SelectedValue;
		$this->SaveData($entity);
		$this->dgrMain->EditItemIndex = -1;
		$this->PopulateDataGrid();
	}
	protected function getVirtualItemCount()
	{
		$result = mysql_query('
			SELECT COUNT(*)
			FROM person p');
		$result = mysql_fetch_row($result);
		return $result[0];
	}
	protected function RetrieveData($offset, $pageSize)
	{
		$sql = '
			SELECT
				p.id,
				p.name,
				p.birthdate,
				p.nameday,
				p.address,
				p.comment,
				p.father,
				p.mother,
				father.name AS father_name,
				mother.name AS mother_name,
				SUBSTRING(p.birthdate, 6, 5) AS birthmonth,
				SUBSTRING(p.nameday, 6, 5) AS namedaymonth,
				p.row_color
			FROM person p
			LEFT JOIN person father ON father.id = p.father
			LEFT JOIN person mother ON mother.id = p.mother
			ORDER BY '.mysql_real_escape_string($this->hdnSortExpression->Value).' '.
			mysql_real_escape_string($this->hdnSortDirection->Value).'
			LIMIT '.$offset.', '.$pageSize;
		$result = mysql_query($sql);
		$resultSet = array();
		while ($row = mysql_fetch_assoc($result))
		{
			$resultSet[] = $row;
		}
		return $resultSet;
	}
	private function SaveRowToHistory($id)
	{
		mysql_query('
			INSERT INTO person_history (
				id, name, address, comment, birthdate, nameday, mother, father, ip_address, host_name, created_on
			)
			SELECT
				p.id, 
				p.name, 
				p.address,
				p.comment,
				p.birthdate, 
				p.nameday, 
				p.mother, 
				p.father, 
				p.ip_address, 
				p.host_name,
				p.created_on
			FROM person p
			WHERE p.id = '.mysql_real_escape_string($id));
		mysql_query('
			DELETE FROM person
			WHERE id = '.mysql_real_escape_string($id));
	}
	protected function DeleteRow($id)
	{
		$this->SaveRowToHistory($id);
	}
	protected function SaveData($value)
	{
		if (empty($value['name'])) $value['name'] = 'NULL';
		else $value['name'] = '\''.mysql_real_escape_string($value['name']).'\'';
		if (empty($value['address'])) $value['address'] = 'NULL';
		else $value['address'] = '\''.mysql_real_escape_string($value['address']).'\'';
		if (empty($value['comment'])) $value['comment'] = 'NULL';
		else $value['comment'] = '\''.mysql_real_escape_string($value['comment']).'\'';
		if (empty($value['row_color'])) $value['row_color'] = 'NULL';
		else $value['row_color'] = '\''.mysql_real_escape_string($value['row_color']).'\'';
		if (empty($value['birthdate'])) $value['birthdate'] = 'NULL';
		else $value['birthdate'] = '\''.mysql_real_escape_string($value['birthdate']).'\'';
		if (empty($value['nameday'])) $value['nameday'] = 'NULL';
		else $value['nameday'] = '\''.mysql_real_escape_string($value['nameday']).'\'';
		if ($value['father']==-1) $value['father'] = 'NULL';
		else $value['father'] = '\''.mysql_real_escape_string($value['father']).'\'';
		if ($value['mother']==-1) $value['mother'] = 'NULL';
		else $value['mother'] = '\''.mysql_real_escape_string($value['mother']).'\'';

		if ((int)$value['id'] !== -1)
		{
			mysql_query('SET FOREIGN_KEY_CHECKS = 0');
			$this->SaveRowToHistory($value['id']);
			mysql_query('
				INSERT INTO person ( 
					id, row_color, name, address, comment, birthdate, nameday, mother, father, ip_address, host_name
				) VALUES (
					'.mysql_real_escape_string($value['id']).',
					'.$value['row_color'].',
					'.$value['name'].',
					'.$value['address'].',
					'.$value['comment'].',
					'.$value['birthdate'].',
					'.$value['nameday'].',
					'.$value['mother'].',
					'.$value['father'].',
					\''.mysql_real_escape_string($_SERVER['REMOTE_ADDR']).'\',
					\''.mysql_real_escape_string(gethostbyaddr($_SERVER['REMOTE_ADDR'])).'\'
				)');
			mysql_query('SET FOREIGN_KEY_CHECKS = 1');
		} else {
			mysql_query('
				INSERT INTO person ( 
					name, address, comment, birthdate, nameday, mother, father, ip_address, host_name
				) VALUES (
					'.$value['name'].',
					'.$value['address'].',
					'.$value['comment'].',
					'.$value['birthdate'].',
					'.$value['nameday'].',
					'.$value['mother'].',
					'.$value['father'].',
					\''.mysql_real_escape_string($_SERVER['REMOTE_ADDR']).'\',
					\''.mysql_real_escape_string(gethostbyaddr($_SERVER['REMOTE_ADDR'])).'\'
				)');
		}
	}
	protected function getParentsList()
	{
		$result = mysql_query('
			SELECT p.id, p.name 
			FROM person p');
		$resultSet = null;
		$resultSet[] = array( 'id' => -1, 'name' => ' ' );
		while ($row = mysql_fetch_assoc($result))
		{
			$resultSet[] = $row;
		}
		return $resultSet;
	}
	protected function btnAddNew_Click($sender, $parameters)
	{
		$dataSet = $this->PopulateDataGridAddNew();
	}
	protected function dgrMain_PageIndexChanged($sender, $parameters)
	{
		$this->dgrMain->EditItemIndex = -1;
		$this->dgrMain->CurrentPageIndex = $parameters->NewPageIndex;
		$this->PopulateDataGrid();
	}
	protected function LocalizeDate($sender)
	{
		if (empty($sender->Parent->Data['birthdate']))
		{
			return '';
		} else {
			$date = strtotime($sender->Parent->Data['birthdate']);
			setlocale(LC_TIME, 'hu');
			return utf8_encode(strftime('%Y. %B '.sprintf("%' 2d", date('j', $date)).'.', $date));
		}
	}
	protected function LocalizeNameday($sender)
	{
		if (empty($sender->Parent->Data['nameday']))
		{
			return '';
		} else {
			$nameDay = strtotime($sender->Parent->Data['nameday']);
			setlocale(LC_TIME, 'hu');
			return utf8_encode(strftime('%B '.sprintf("%' 2d", date('j', $nameDay)).'.', $nameDay));
		}
	}
	private function SaveToLog($content)
	{
		$result = mysql_query('INSERT INTO log (content) VALUES (\''.mysql_real_escape_string($content).'\')');
	}
	protected function dgrMain_SortCommand($sender, $parameters)
	{
		$this->SortGrid($parameters->SortExpression);
	}
	private function SortGrid($sortExpression)
	{
		$this->dgrMain->EditItemIndex = -1;
		if ($this->hdnSortExpression->Value !== $sortExpression)
		{
			if ($sortExpression !== $this->rowColorSortExpression)
				$this->hdnSortDirection->Value = $this->defaultSortDirection;
			else
				$this->hdnSortDirection->Value = 'DESC';
		} else {
			if ($this->hdnSortDirection->Value === 'ASC') $this->hdnSortDirection->Value = 'DESC';
			else $this->hdnSortDirection->Value = 'ASC';
		}
		$this->hdnSortExpression->Value = $sortExpression;
		$this->PopulateDataGrid();
	}
	protected function btnSortByBirthMonth_Click($sender, $parameters)
	{
		$this->SortGrid('birthmonth');
	}
	protected function btnSortByRowColor_Click($sender, $parameters)
	{
		$this->SortGrid($this->rowColorSortExpression);
	}
	protected function dgrMain_ItemCreated($sender, $parameters)
	{
		if ($parameters->Item->ItemType === 'Header')
		{
			for ($i = 0; $i < $this->dgrMain->Columns->Count; $i++)
			{
				if ($this->dgrMain->Columns[$i]->SortExpression === $this->hdnSortExpression->Value)
				{
					$image = new TImage();
					if ($this->hdnSortDirection->Value === 'ASC')
						$image->ImageUrl = 'images/smallest-to-bigest.png';
					else
						$image->ImageUrl = 'images/bigest-to-smallest.png';
					$literal = new TLiteral();
					$literal->Text = '&nbsp;';
					$parameters->Item->Cells[$i]->Controls->add($literal);
					$parameters->Item->Cells[$i]->Controls->add($image);
				}
			}
		}
		else if ($parameters->Item->ItemType === 'Item' || 
			$parameters->Item->ItemType === 'AlternatingItem' ||
			$parameters->Item->ItemType === 'EditItem')
		{
			if (!empty($parameters->Item->Data['row_color']))
				$parameters->Item->BackColor = $parameters->Item->Data['row_color'];
			$parameters->Item->dgrMain_DeleteCommand->Button->Attributes->onclick = 
				'if(!confirm(\'Biztos törölni szeretnéd ezt a sort: '.$parameters->Item->Data['name'].'?\')) return false;';
		}
	}
	protected function ddlPageSize_SelectedIndexChanged($sender, $parameters)
	{
		$this->dgrMain->PageSize = $this->ddlPageSize->SelectedValue;
		$this->dgrMain->DataSource = $this->PopulateDataGrid();
		$this->dgrMain->DataBind();
	}
}
?>